use log::error;
use ylong_runtime::net::TcpStream;

use crate::{
    common::{hdc_command::HdcCommand, hdc_error::HdcError, task_message::TaskMessage, tcp_connect::TcpConnect},
    param::Param,
};

pub struct Client<F>
where F: Fn(Vec<u8>)
{
    server: TcpConnect,
    #[allow(unused)]
    param: Param,
    out_callback: F
}

impl<F> Client<F>
where F: Fn(Vec<u8>)
{
    pub async fn new(param: Param, out_callback: F) -> Option<Self> {
        let Ok(stream) = TcpStream::connect(param.get_server_add()).await else {
            error!("connect server filed");
            return None;
        };
        let server = TcpConnect::new(stream);

        Some(Self { server, param, out_callback })
    }

    #[allow(unused)]
    fn client_print(&self, data: Vec<u8>) {
        (self.out_callback)(data);
    }

    /// 在该函数中写入进程相关的所有逻辑
    pub async fn execute_command(&mut self) -> Result<(), HdcError> {
        let data = "test str, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".to_owned();
        let msg = TaskMessage { channel_id: 0, command: HdcCommand::Daemon, payload: data.as_bytes().to_vec() };
        self.server.write_message(msg).await?;
        // match self.server.read_msg().await {
        //     Ok(msg) => {
        //         log::info!("recv {msg:?}");
        //         Ok(())
        //     },
        //     Err(err) => Err(err),
        // }
        Ok(())
    }
}
